
#1,sku序列化器
from goods.models import SKU,SPU,GoodsCategory,SpecificationOption,SPUSpecification
from rest_framework import serializers
from django.db import transaction

# 规格选项序列化器
class SKUSpecificationSerializers(serializers.Serializer):
    # 1,spu,spu_id

    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

# 1.sku序列化器
class SKUSerializer(serializers.ModelSerializer):
    #1,spu,spu_id
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    #2,category,category_id
    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()

     #3,匹配规格选项
    # specs = SKUSpecificationSerializer(read_only=True,many=True)
    class Meta:
        model = SKU
        fields = "__all__"



    # 4.重写create方法，保存规格信息
    @transaction.atomic
    def create(self,validated_data):
        sid = transaction.savepoint() #TODO 设置保存点
        try:
            #1,将sku创建,并入库
            sku = SKU.objects.create(**validated_data)


            # 2,sku,specifiction入库
            specs = self.context['request'].data['specs']
            for spec_dict in specs:
                SKUSpecification.objects.create(sku_id=sku.id, spec_id=spec_dict["spec_id"],
                                                option_id=spec_dict["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)  # TODO 回滚
            raise serializers.ValidationError("sku添加异常")
        else:
            # 3,返回响应
            transaction.savepoint_commit(sid)  # TODO 提交
            return sku



    # 5.重写updata方法，更改规格数据
    @transaction.atomic
    def  updata(self,instance,validated_data):
        sid = transaction.savepoint()   # TODO 设置保存点

        try:
            # 1,更改sku基础信息(名称,价格..)
            SKU.objects.filter(id=instance.id).update(**validated_data)

            # 2,更改规格信息
            # 删除以前的规格
            [spec.delete() for spec in instance.specs.all()]

            # 创建新的规格
            specs = self.context["request"].data["specs"]
            for spec_dict in specs:
                SKUSpecification.objects.create(sku_id=instance.id, spec_id=spec_dict["spec_id"],
                                                option_id=spec_dict["option_id"])
        except Exception as e:
            transaction.savepoint_rollback(sid)  # TODO 回滚
            raise serializers.ValidationError("sku修改异常")
        else:
            # 3,返回响应
            transaction.savepoint_commit(sid)  # TODO 提交
            return SKU.objects.get(id=instance.id)



# sku 分类数据
class SKUCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"

#3,sku,spu序列化器
class SKUSPUSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ("id","name")


# 选项序列化器
class SPUSpecificationOption(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ("id","value")


##4,spu specification序列化器
class SPUSpecificationSerializer(serializers.ModelSerializer):

    #1,选项字段
    options = SPUSpecificationOption(read_only=True,many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"



# 规格选项序列化器
class SKUSpecificationSerializers(serializers.Serializer):

    # 1,spu,spu_id

    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()



